<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色按钮 -->
    <el-card class="box-card">
      <el-button type="primary">添加角色</el-button>
    </el-card>
    <!-- 渲染数据列表 -->
    <el-table ref="singleTable" border :data="rolesData" highlight-current-row style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 一级渲染列表权限 -->
          <el-row
            v-for="(item, index) in scope.row.children"
            :key="index"
            :class="['borbtn',index == 0 ? 'bortop':'']"
          >
            <el-col :span="5" class="grid-content bg-purple">
              <el-tag
                type="warning"
                closable
                @close="delChilren(scope.row,item.id)"
              >{{item.authName}}</el-tag>
            </el-col>
            <el-col :span="19">
              <!-- 二级列表 -->
              <el-row
                class="grid-content bg-purple"
                v-for="(item2, index) in item.children"
                :key="index"
              >
                <el-col :span="5">
                  <el-tag closable @close="delChilren(scope.row,item2.id)">{{item2.authName}}</el-tag>
                </el-col>
                <el-col :span="19">
                  <!-- 三级列表 -->
                  <el-row>
                    <el-col :class="['borbtn']">
                      <el-tag
                        v-for="(item3, index) in item2.children"
                        :key="index"
                        closable
                        @close="delChilren(scope.row,item3.id)"
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <pre>
            <!-- {{scope.row.id}} -->
          </pre>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column property="roleName" label="角色名称"></el-table-column>
      <el-table-column property="roleDesc" label="角色描述"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
          <el-button
            size="mini"
            type="info"
            icon="el-icon-s-tools"
            @click="rightList(scope.row)"
          >权限设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 点击权限设置弹出的对话框 -->
    <el-dialog title="权限设置" :visible.sync="dialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree
        current-node-key
        :data="rightData"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        :props="defaultProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
           
<script>
import {
  authorityUser,
  deleRolesId,
  getRightsList,
  getImpowerRole,
  deleteRights
} from "@/api";
export default {
  data() {
    return {
      //获取角色列表
      rolesData: [],
      // 获取全部权限列表
      rightData: [],
      // 接受获取到用户的权限列表
      defKeys: [],
      // 判断对话框是否显示
      dialogVisible: false,
      // 渲染权限数据
      defaultProps: {
        children: "children",
        label: "authName"
      },
      //被分配权限的用户id
      roleId: ""
    };
  },
  methods: {
    // 获取角色列表
    async getAuthority() {
      var { data: res } = await authorityUser();
      // console.log(res, 9999);
      this.rolesData = res.data;
    },
    // 删除权限列表中的单个元素
    async delChilren(params, id) {
      var aa = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {}
      ).catch(err => err);
      if (aa !== "confirm") {
        return this.$message.info("用户点击了取消按钮");
      }
      if (aa === "confirm") {
        var { data: res } = await deleRolesId({
          roleId: params.id,
          rightId: id
        });
        if (res.meta.status !== 200) return this.$message.error("删除权限失败");
        this.$message.error("删除权限成功");
        // console.log(res);
        params.children = res.data;
      }
    },
    // 获取角色对应的权限  通过递归获取
    getRightsListUser(role, arr) {
      if (!role.children) {
        return arr.push(role.id);
      }
      //如果还有children就循环调用该函数
      role.children.forEach(item => {
        this.getRightsListUser(item, arr);
      });
    },
    //点击取消或者是关闭清空角色对应的权限数据
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 获取权限列表
    async rightList(role) {
      this.roleId = role.id;
      var { data: res } = await getRightsList("tree");
      // console.log(res.data,99);
      this.rightData = res.data;
      this.getRightsListUser(role, this.defKeys);
      // console.log(this.defKeys,9999);
      this.dialogVisible = true;
    },
    // 点击确认修改权限功能
    async allotRights() {
      //获取选中的和半选中的数据
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      //以，分割为string类型
      let str = keys.join(",");
      //调用接口修改权限
      var { data: res } = await getImpowerRole(this.roleId, str);
      // console.log(res, 9090);
      //判断是否成功  200代表成功
      if (res.meta.status !== 200) return this.$message.error("授权失败！");

      this.$message.info("授权成功！");
      //重新加载数据  相当于更新数据
      this.getAuthority();
      //关闭对话框
      this.dialogVisible = false;
    },
    //点击删除按钮点击删除
    async deleteRoles(id) {
      // deleteRights(id);
      var state = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      // console.log(aa);
      if (state == "confirm") {
        var { data: res } = await deleteRights(id);
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        this.$message.success("删除成功");
        this.getAuthority();
      }
    }
  },
  created() {
    this.getAuthority();
  }
};
</script>
<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.bortop {
  border-top: 1px solid #ccc;
}
.borbtn {
  border-bottom: 1px solid #ccc;
}
.el-tag {
  margin: 7px;
}
</style>